import 'package:flutter/material.dart';
import '../models/exam_model.dart';
import '../models/student_model.dart';
import '../models/question_model.dart';
import '../services/exam_state_service.dart';
import '../services/student_service.dart';
import '../utils/responsive_util.dart';
import 'answer_details_screen.dart';

class StudentResultsScreen extends StatefulWidget {
  final Exam exam;

  const StudentResultsScreen({
    super.key,
    required this.exam,
  });

  @override
  State<StudentResultsScreen> createState() => _StudentResultsScreenState();
}

class _StudentResultsScreenState extends State<StudentResultsScreen> {
  List<ExamResult> _studentResults = [];
  bool _isLoading = true;
  String _searchQuery = '';
  Map<String, Student> _studentMap = {};

  @override
  void initState() {
    super.initState();
    _loadStudentResults();
  }

  Future<void> _loadStudentResults() async {
    setState(() {
      _isLoading = true;
    });

    try {
      // 加载所有学生
      await StudentService.init();
      final students = StudentService.getStudents();
      
      // 创建学生ID到学生对象的映射
      for (var student in students) {
        _studentMap[student.id] = student;
      }
      
      // 获取该考试的所有学生结果
      final results = await ExamStateService.getAllStudentResultsForExam(widget.exam.id);
      
      setState(() {
        _studentResults = results;
        _isLoading = false;
      });
    } catch (e) {
      debugPrint('加载学生考试结果失败: $e');
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 根据搜索查询过滤学生结果
  List<ExamResult> get _filteredResults {
    if (_searchQuery.isEmpty) {
      return _studentResults;
    }
    
    return _studentResults.where((result) {
      // 尝试获取学生信息
      final student = _studentMap[result.userId];
      if (student == null) {
        return false;
      }
      
      // 按学生ID或姓名搜索
      return student.id.toLowerCase().contains(_searchQuery.toLowerCase()) ||
             student.name.toLowerCase().contains(_searchQuery.toLowerCase());
    }).toList();
  }

  // 获取学生信息
  Student? _getStudentById(String userId) {
    return _studentMap[userId];
  }

  @override
  Widget build(BuildContext context) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '学生答题记录',
          style: TextStyle(
            fontSize: isTablet ? 22 : 20,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
        backgroundColor: Colors.blue.shade800,
        actions: [
          IconButton(
            icon: Icon(Icons.search),
            onPressed: () {
              showSearch(
                context: context,
                delegate: _StudentSearchDelegate(
                  studentResults: _studentResults,
                  studentMap: _studentMap,
                  onResultTap: _viewStudentResult,
                ),
              );
            },
          ),
        ],
      ),
      body: _isLoading
          ? Center(child: CircularProgressIndicator())
          : _studentResults.isEmpty
              ? Center(
                  child: Text(
                    '暂无学生完成此考试',
                    style: TextStyle(
                      fontSize: isTablet ? 18 : 16,
                      color: Colors.grey.shade600,
                    ),
                  ),
                )
              : ListView.builder(
                  padding: EdgeInsets.all(16),
                  itemCount: _filteredResults.length,
                  itemBuilder: (context, index) {
                    final result = _filteredResults[index];
                    return _buildStudentResultCard(result);
                  },
                ),
    );
  }

  Widget _buildStudentResultCard(ExamResult result) {
    final student = _getStudentById(result.userId);
    final bool isTablet = ResponsiveUtil.isTablet(context);
    
    return Card(
      margin: EdgeInsets.only(bottom: 12),
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: InkWell(
        onTap: () => _viewStudentResult(result),
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  CircleAvatar(
                    backgroundColor: Colors.blue.shade100,
                    child: Text(
                      student?.name.substring(0, 1) ?? '?',
                      style: TextStyle(
                        color: Colors.blue.shade800,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          student?.name ?? '未知学生',
                          style: TextStyle(
                            fontSize: isTablet ? 18 : 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(height: 4),
                        Text(
                          '学号: ${student?.id ?? result.userId}',
                          style: TextStyle(
                            fontSize: isTablet ? 14 : 12,
                            color: Colors.grey.shade700,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              SizedBox(height: 16),
              // 客观题统计
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '客观题统计',
                    style: TextStyle(
                      fontSize: isTablet ? 15 : 13,
                      fontWeight: FontWeight.bold,
                      color: Colors.blue.shade800,
                    ),
                  ),
                  SizedBox(height: 8),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      _buildStatCard(
                        context,
                        title: '总题数',
                        value: _getObjectiveQuestionCount().toString(),
                        color: Colors.blue,
                        isTablet: isTablet,
                      ),
                      _buildStatCard(
                        context,
                        title: '已答题',
                        value: _getAnsweredObjectiveQuestionCount(result).toString(),
                        color: Colors.orange,
                        isTablet: isTablet,
                      ),
                      _buildStatCard(
                        context,
                        title: '正确数',
                        value: _getCorrectObjectiveQuestionCount(result).toString(),
                        color: Colors.green,
                        isTablet: isTablet,
                    ),
                    ],
                  ),
                ],
              ),
              SizedBox(height: 12),
                  Text(
                    '提交时间: ${result.submittedAt != null ? _formatDateTime(result.submittedAt!) : '未知'}',
                style: TextStyle(
                  fontSize: isTablet ? 14 : 12,
                  color: Colors.grey.shade700,
                  ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 构建统计卡片
  Widget _buildStatCard(BuildContext context, {
    required String title,
    required String value,
    required MaterialColor color,
    required bool isTablet,
  }) {
    return Container(
      width: MediaQuery.of(context).size.width * 0.25,
      padding: EdgeInsets.symmetric(vertical: 8, horizontal: 12),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: color.withOpacity(0.3)),
      ),
      child: Column(
        children: [
          Text(
            title,
            style: TextStyle(
              fontSize: isTablet ? 13 : 11,
              color: color.shade700,
            ),
          ),
          SizedBox(height: 4),
          Text(
            value,
            style: TextStyle(
              fontSize: isTablet ? 18 : 16,
              fontWeight: FontWeight.bold,
              color: color.shade800,
            ),
          ),
        ],
      ),
    );
  }

  // 获取客观题总数
  int _getObjectiveQuestionCount() {
    return widget.exam.questions.where((q) => 
      q.type == QuestionType.singleChoice || 
      q.type == QuestionType.multipleChoice || 
      q.type == QuestionType.trueOrFalse
    ).length;
  }

  // 获取已答客观题数量
  int _getAnsweredObjectiveQuestionCount(ExamResult result) {
    int count = 0;
    for (var question in widget.exam.questions) {
      if ((question.type == QuestionType.singleChoice || 
           question.type == QuestionType.multipleChoice || 
           question.type == QuestionType.trueOrFalse) && 
          result.answers.containsKey(question.id)) {
        count++;
      }
    }
    return count;
  }

  // 获取正确的客观题数量
  int _getCorrectObjectiveQuestionCount(ExamResult result) {
    int count = 0;
    for (var question in widget.exam.questions) {
      if (question.type == QuestionType.singleChoice || 
          question.type == QuestionType.multipleChoice || 
          question.type == QuestionType.trueOrFalse) {
        
        final userAnswer = result.answers[question.id];
        if (userAnswer != null) {
          if (_isAnswerCorrect(question, userAnswer)) {
            count++;
          }
        }
      }
    }
    return count;
  }

  // 检查答案是否正确
  bool _isAnswerCorrect(Question question, dynamic userAnswer) {
    if (question.type == QuestionType.singleChoice) {
      final q = question as SingleChoiceQuestion;
      // Get the choice with the correct index
      final correctChoice = q.choices[q.correctOption];
      return userAnswer == correctChoice.id;
    } else if (question.type == QuestionType.multipleChoice) {
      final q = question as MultipleChoiceQuestion;
      if (userAnswer is List) {
        // Get all correct choice IDs
        final correctChoiceIds = q.correctOptions.map((index) => q.choices[index].id).toList();
        final userSet = Set.from(userAnswer);
        final correctSet = Set.from(correctChoiceIds);
        return userSet.length == correctSet.length && userSet.containsAll(correctSet);
      }
      return false;
    } else if (question.type == QuestionType.trueOrFalse) {
      final q = question as TrueOrFalseQuestion;
      return userAnswer == q.correctAnswer;
    }
    return false;
  }

  // 查看学生详细答题记录
  void _viewStudentResult(ExamResult result) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => AnswerDetailsScreen(
          exam: widget.exam,
          result: result,
          isAdminView: true,
        ),
      ),
    );
  }

  // 格式化日期时间
  String _formatDateTime(DateTime dateTime) {
    return '${dateTime.month}-${dateTime.day} ${dateTime.hour}:${dateTime.minute}';
  }
}

// 学生搜索代理
class _StudentSearchDelegate extends SearchDelegate<ExamResult?> {
  final List<ExamResult> studentResults;
  final Map<String, Student> studentMap;
  final Function(ExamResult) onResultTap;

  _StudentSearchDelegate({
    required this.studentResults,
    required this.studentMap,
    required this.onResultTap,
  });

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: Icon(Icons.clear),
        onPressed: () {
          query = '';
        },
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: Icon(Icons.arrow_back),
      onPressed: () {
        close(context, null);
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return _buildSearchResults();
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return _buildSearchResults();
  }

  Widget _buildSearchResults() {
    if (query.isEmpty) {
      return Center(child: Text('请输入学生姓名或学号'));
    }

    final List<ExamResult> filteredResults = studentResults.where((result) {
      final student = studentMap[result.userId];
      if (student == null) {
        return false;
      }
      
      return student.id.toLowerCase().contains(query.toLowerCase()) ||
             student.name.toLowerCase().contains(query.toLowerCase());
    }).toList();

    if (filteredResults.isEmpty) {
      return Center(child: Text('未找到匹配的学生'));
    }

    return ListView.builder(
      itemCount: filteredResults.length,
      itemBuilder: (context, index) {
        final result = filteredResults[index];
        final student = studentMap[result.userId];
        
        return ListTile(
          leading: CircleAvatar(
            backgroundColor: Colors.blue.shade100,
            child: Text(
              student?.name.substring(0, 1) ?? '?',
              style: TextStyle(
                color: Colors.blue.shade800,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          title: Text(student?.name ?? '未知学生'),
          subtitle: Text('学号: ${student?.id ?? result.userId}'),
          trailing: Text(
            '提交时间: ${result.submittedAt != null ? _formatDateTime(result.submittedAt!) : '未知'}',
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey.shade700,
            ),
          ),
          onTap: () {
            close(context, result);
            onResultTap(result);
          },
        );
      },
    );
  }

  // 格式化日期时间
  String _formatDateTime(DateTime dateTime) {
    return '${dateTime.month}-${dateTime.day} ${dateTime.hour}:${dateTime.minute}';
  }
} 